package org.example.springtrans.controller;

import org.example.springtrans.model.UserInfo;
import org.example.springtrans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/2
 * Time: 20:11
 */
@RestController
@RequestMapping("/trans")
public class TransController {

    @Autowired
    private UserService userService;

    @Transactional
    @RequestMapping("/t1")
    public Boolean test1(UserInfo userInfo){
        userService.register(userInfo);
        throw new RuntimeException();//触发回滚
    }

    @Transactional
    @RequestMapping("/t2")
    public Boolean test2(UserInfo userInfo){
        Integer result = userService.register(userInfo);
        try {
            throw new RuntimeException();//不触发回滚
        }catch (RuntimeException e){
            e.printStackTrace();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result >= 0;
    }

    @Transactional
    @RequestMapping("/t3")
    public Boolean test3 (UserInfo userInfo) throws IOException{
        Integer result = userService.register(userInfo);
        if(true) {
            throw new IOException();//不触发回滚
        }
        return result >= 0;
    }

    @Transactional
    @RequestMapping("/t4")
    public Boolean test4(UserInfo userInfo){
        Integer result = userService.register(userInfo);
        try {
            throw new IOException();//不触发回滚
        }catch (IOException e){
            e.printStackTrace();
        }
        return result >= 0;
    }
}
